package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList; 
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import bsi.vn.Data.ATMData;
import bsi.vn.Data.ContractATMListAdapter;
import bsi.vn.Data.ContractAdapter;
import bsi.vn.Data.ContractData;
import bsi.vn.Data.CookieData;
import bsi.vn.Data.CustomerData;
import bsi.vn.Data.CustomerSpinnerAdapter;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

public class ContractSearchActivity extends Activity implements OnClickListener, OnScrollListener {
	Spinner glo_snCustomer;
	private View glo_vSearchCondition;
	private View glo_vResult;
	private EditText txtSearchKey;
	private Button btnSearch;
	private ArrayList<ContractData> contractList;
	private ContractAdapter adapter;
	private Spinner spinner;
	private ListView lvContract;
	
	private int a ;
	private int b ;
	private int flag;
	private int size = 50;
	private ArrayList<ContractData> templist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contract_search);

		flag = 0;
		a  = 0;
		b = 0;
		templist = new ArrayList<ContractData>();
		
		
		glo_vSearchCondition = findViewById(R.id.csllSearchCondition);
		glo_vResult = findViewById(R.id.csllResult);

		btnSearch = (Button) findViewById(R.id.csbtSearch);
		btnSearch.setOnClickListener(this);
		spinner = (Spinner) findViewById(R.id.cssnCustomer);

		glo_snCustomer = (Spinner) findViewById(R.id.cssnCustomer);
		ArrayAdapter<CustomerData> cusAdapter = new CustomerSpinnerAdapter(
				this, R.layout.spinner_row, ProcessFunc.GetCustomer(this));
		glo_snCustomer.setAdapter(cusAdapter);
		
		lvContract = (ListView) findViewById(R.id.cslvContractList);
		lvContract.setOnScrollListener(this);
		lvContract.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent general = new Intent(ContractSearchActivity.this, TabContractDetailActivity.class);
				ContractData i = (ContractData) arg0.getItemAtPosition(arg2);
				Bundle a = new Bundle();
				a.putInt("CTID", i.getContractId());
				general.putExtra("mypack", a);
				startActivity(general);
				
			}
		});
		
		findViewById(R.id.csbtDisplaySearch).setOnClickListener(this);
//				new View.OnClickListener() {
//					@Override
//					public void onClick(View view) {
//						glo_vSearchCondition.setVisibility(View.VISIBLE);
//						glo_vResult.setVisibility(View.INVISIBLE);
//					}
//				});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.atmsearch, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() != R.id.menu_contract && item.getItemId() != R.id.menu_sub){
			startActivity(ProcessFunc.MenuAction(this, item));
		}
		
		return true;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.csbtDisplaySearch:
			glo_vSearchCondition.setVisibility(View.VISIBLE);
			glo_vResult.setVisibility(View.INVISIBLE);
			break;
		case R.id.csbtSearch:
			ProcessFunc.hideSoftKeyboard(ContractSearchActivity.this);
			contractList = new ArrayList<ContractData>();

			glo_vSearchCondition.setVisibility(View.INVISIBLE);
			glo_vResult.setVisibility(View.VISIBLE);

			txtSearchKey = (EditText) findViewById(R.id.csedContractNo);
			Editable strSearch = txtSearchKey.getText();
			// String customer = "BVB";
			// String contractNo = "1112/2009/BSI-BVB";
			Log.d("test", strSearch.toString());
			myContractList myWebFetch = new myContractList();
			myWebFetch
					.execute(new String[] {
							strSearch.toString(),
							(((CustomerData) spinner.getSelectedItem()).getId())
									+ "" });
			break;

		default:
			break;
		}
//		
//		if (v.getId() == R.id.csbtDisplaySearch) {
//			glo_vSearchCondition.setVisibility(View.VISIBLE);
//			// glo_vResult.setVisibility(View.INVISIBLE);
//		} else {
//
//			ProcessFunc.hideSoftKeyboard(ContractSearchActivity.this);
//			contractList = new ArrayList<ContractData>();
//
//			glo_vSearchCondition.setVisibility(View.INVISIBLE);
//			glo_vResult.setVisibility(View.VISIBLE);
//
//			txtSearchKey = (EditText) findViewById(R.id.csedContractNo);
//			Editable strSearch = txtSearchKey.getText();
//			// String customer = "BVB";
//			// String contractNo = "1112/2009/BSI-BVB";
//			Log.d("test", strSearch.toString());
//			myContractList myWebFetch = new myContractList();
//			myWebFetch
//					.execute(new String[] {
//							strSearch.toString(),
//							(((CustomerData) spinner.getSelectedItem()).getId())
//									+ "" });
//		}
	}

	private class myContractList extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String data = "";
			try {

				data = GetContractList(params[0], params[1]);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}

		@Override
		protected void onPostExecute(String result) {
			String loc_arResponse[] = result.split("\\|");
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]);
			if (loc_iResponseCode == Consts.RC_LOGOUT) {
				startActivity(new Intent(ContractSearchActivity.this,
						LoginActivity.class));
				return;
			}
			if (loc_iResponseCode == Consts.RC_ERROR) {
				ProcessFunc.ShowSimpleDialog(ContractSearchActivity.this,
						"Error", loc_arResponse[1]);
				return;
			}

			try {
				JSONArray jArray = new JSONArray(loc_arResponse[1]);
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject json_data = jArray.getJSONObject(i);
					ContractData coData = new ContractData();
					Log.d("test", "lengh " + jArray.length());

					coData.setContractId(json_data
							.getInt(Consts.SDB_CONTRACTID));
					coData.setContractNo(json_data
							.getString(Consts.SDB_CONTRACTNO));
					coData.setExpireDate(json_data
							.getString(Consts.SDB_EXPIREDATE));
					coData.setCustomer(json_data.getString(Consts.SDB_CUSTOMER));

					contractList.add(coData);

				}
				if(contractList.size() > 50){
					for(int i = 0; i< 50;i++){
						templist.add(contractList.get(i));
					}
					adapter = new ContractAdapter(ContractSearchActivity.this,
							R.layout.contract_detail_item, templist);
					
					lvContract.setAdapter(adapter);
					Log.d("test", templist.size()+"");
				}else{
					adapter = new ContractAdapter(ContractSearchActivity.this,
							R.layout.contract_detail_item, contractList);
					lvContract.setAdapter(adapter);
					Log.d("test", contractList.size()+"");
				}
			} catch (JSONException e) {
				Log.e("test", "Error parsing data " + e.toString());
			}

			
			
			lvContract.setAdapter(adapter);

			// lvTicket.setOnItemClickListener(new OnItemClickListener() {
			// @Override
			// public void onItemClick(AdapterView<?> parent, View view,
			// int position, long id) {
			// int TicketId = ticketData.get(position).getTicketId();
			// Intent i = new Intent(getApplicationContext(),
			// TicketDetailActivity.class);
			// i.putExtra("TicketId", TicketId);
			// startActivity(i);
			// }
			// });
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(String... text) {
		}

	}

	private String GetContractList(String contractNo, String customer) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc
					.GetCookie(ContractSearchActivity.this);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_CONTRACTSEARCH));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String
					.valueOf(cookie.getUserId())));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));
			nameValuePair.add(new BasicNameValuePair(Consts.V_CONTRACTNO,
					contractNo + ""));
			nameValuePair.add(new BasicNameValuePair(Consts.V_CUSTOMER,
					customer + ""));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"), 16);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("test", "Error converting result " + e.toString());
		}
		return result;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		loadLimit(firstVisibleItem, visibleItemCount, totalItemCount);
		
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		
	}

	public void loadLimit(int firstVisibleItem, int visible, int totalcount){
		if(totalcount - visible == firstVisibleItem && firstVisibleItem > flag){
			flag +=  (totalcount - visible);
//			loadSize(50);
			a = templist.size();
			if((contractList.size() -a >= 50) ){
				b = a + size;
			}else{
				b = contractList.size();
			}
			
			Log.d("test", "a =  " + a);
			Log.d("test", "b =  " + b);
			Log.d("test", "active at " + firstVisibleItem);
			for(int i = a; i< b;i++){
				templist.add(contractList.get(i));
			}
			adapter.notifyDataSetChanged();
		}		
	}

}
